<template>
    <a-tooltip :content="!isRecording ? '视频录制' : ' 停止录制'"
               background-color="rgba(0,0,0,0.6)"
               :content-style="{padding:'0.05rem .1rem'}">
        <icon-live-broadcast v-if="!isRecording" @click="handleController" />
        <icon-record-stop style="color: red"  v-if="isRecording" @click="handleController" />
    </a-tooltip>
    <a-modal width="auto"
             v-model:visible="visible"
             title-align="start"
             :title="state.blobTitle"
             ok-text="下载"
             @ok="handleOk"
             @cancel="handleCancel"
             @open="modalOpen">
        <div :id="`preview_${state.videoId}`" class="preview_video"></div>
    </a-modal>
</template>

<script setup>

    import moment from 'moment'

    const props = defineProps({
        name: {
            type: String,
            default:()=>'',
            required: true
        },
        options: {
            type: Object,
            default:()=>new Object(),
            required: true
        },
        index: {
            type: Number,
            default:()=>0,
            required: true
        },
    })

    const isRecording = ref(false)
    const visible = ref(false)

    const state = reactive({

        videoId:'',

        // 缓存当前录屏对象
        recordRTC:null,

        // 缓存当前录屏的文件流
        blob:null,

        // 设置当前录屏的文件名
        blobTitle:''
    })

    // 录屏
    const handleController=()=>{
        const { urlEncoded } = props.options
        const id = urlEncoded[props.index]
        state.videoId= `preview_${id}`
        if(!isRecording.value){
            startRecording(id)
        }else{
            stopRecording()
        }
    }

    // 开始录屏
    const startRecording=(id)=>{
        let element = document.getElementById(id).querySelector(`.dplayer-video`);
        let stream = null
        if (element.captureStream) { // 适用于chrome内核
            stream = element.captureStream();
        } else if (element.mozCaptureStream) { // 适用于firefox内核
            stream = element.mozCaptureStream();
        }else{
            $message.error('您的浏览器暂不支持录屏！')
            return false
        }
        state.recordRTC = RecordRTC(stream, {type: 'video'})
        isRecording.value = true
        state.recordRTC.startRecording();
    }

    // 结束录屏 , 打开预览弹框
    const stopRecording = ()=>{
        isRecording.value = false
        state.recordRTC.stopRecording( async ()=> {
            // 生成当前录屏的文件流
            let blob = await state.recordRTC.getBlob();
            state.blob=window.URL.createObjectURL(blob)
            state.blobTitle=`${moment().format('YYYY-MM-DD HH:mm:ss')}.mp4`
            visible.value = true
        })
    }

    // 打开弹框后的回调，dom 渲染完成后执行初始化video 操作
    const modalOpen=()=>{
        setTimeout(()=>{
            console.log(document.getElementById('preview'),)
            setVideoOptions(state.blob)
        },500)

    }


    // 初始化录屏预览设置
    const setVideoOptions = (url)=>{
        const options = {
            autoplay:true, // 自动播放
            mutex:false, // 关闭互斥
            hotkey:false,
            chromecast:true,
            screenshot:true,  // 开启截图
            container: document.getElementById(`preview_${state.videoId}`),
            video:{url}
        }
        const dp =  new DPlayer(options)
        dp.play()
    }


    // 下载
    const handleOk=()=>{
        // 创建一个临时的URL指向Blob对象

        // 创建一个a标签用于下载
        let downloadLink = document.createElement('a');
        downloadLink.href = state.blob;
        downloadLink.download = state.blobTitle  ; // 指定下载文件名

        // 触发a标签的点击事件，开始下载
        document.body.appendChild(downloadLink);
        downloadLink.click();
        // 清理临时的URL和下载链接
        document.body.removeChild(downloadLink);
        window.URL.revokeObjectURL(state.blob);

        handleCancel()
    }

    // 取消
    const handleCancel=()=>{
        state.recordRTC = null
        state.blob = null
        state.blobTitle = ''
        visible.value = false
    }


</script>

<style scoped lang="less">
    .preview_video{
        width: 65vw;
        height: 60vh;
         video {
            width: 100%;
            height: 100%;
            object-fit: fill;
        }
    }

</style>